/*
 * 封装异步请求ajax 
 */
function ajax(options) {
	options = options || {};
	options.type = (options.type || 'GET').toUpperCase();
	options.dataType = options.dataType || 'json';
    //options.async = options.async || true;
	options.async = options.async==undefined ? true : options.async;
	options.contentType = options.contentType || 'application/x-www-form-urlencoded';
	var params = options.data;
	var xhr;
	
	if(window.XMLHttpRequest) {
		xhr = new XMLHttpRequest();
	} else {
		xhr = new ActiveXObject('Microsoft.XMLHTTP');
	}
	
	xhr.onreadystatechange = function() {
		if(xhr.readyState == 4) {
			var status = xhr.status;
			if(status >=200 && status < 300) {
				options.success && options.success(xhr.responseText, xhr.getResponseHeader('etag'));
			} else {
				options.error && options.error(status);
			}
		}
	}
	
	if(options.type == 'GET' || options.type == 'DELETE') {
		var paramsEncode = encodeData(params);
		xhr.open(options.type, options.url + '?' + paramsEncode, options.async);
		xhr.send(null);
	} else if(options.type == 'POST' || options.type == 'PUT') {
		xhr.open(options.type, options.url, options.async);
		xhr.setRequestHeader('Content-Type',options.contentType);
		var extHeaders = options.header;
        if (extHeaders) {
            for (var key in extHeaders) {
                xhr.setRequestHeader(key, extHeaders[key]);
            }
        }
		if(options.contentType == 'application/json' || options.contentType == 'binary/octet-stream') {
			xhr.send(params)
		} else {
			if(typeof FormData == 'function') {
				var formData = new FormData();
				for(var key in params) {
					formData.append(key, params[key]);
				}
				xhr.send(formData);
			} else {
				var paramsEncode = encodeData(params);
				xhr.send(paramEncode);
			}
		}
	}
}

function encodeData(data) {
	var arr = [];
	for(var param in data) {
		arr.push(encodeURIComponent(param) + '=' + encodeURIComponent(data[param]));
	}
	return arr.join('&');
}